package com.soriya.nestlive.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.soriya.nestlive.db.dao.UserInfoDao
import com.soriya.nestlive.im.ImHandler
import com.soriya.nestlive.im.MessageType
import com.soriya.nestlive.im.NettyClient
import com.soriya.nestlive.im.message.IMMessage
import com.soriya.nestlive.model.LiveChat
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LiveChatModel @Inject constructor(
    private val userInfoDao: UserInfoDao,
    private val _nettyClient: NettyClient,
    private val imHandler: ImHandler
) : ViewModel() {

    val channel = Channel<LiveChat>(10, onBufferOverflow = BufferOverflow.SUSPEND)

    private lateinit var chatHandler: (IMMessage) -> Unit

    val nettyClient = _nettyClient

    @OptIn(ExperimentalCoroutinesApi::class)
    fun liveChat(channelId: Long): Channel<LiveChat> {

        chatHandler = {
            viewModelScope.launch {
                val message =
                    LiveChat(
                        id = 0,
                        userId = it.from,
                        nickname = it.nickname ?: "未知用户",
                        liveId = it.to,
                        content = it.data ?: "",
                        type = it.type
                    )
                if (channel.isClosedForSend) return@launch
                channel.send(message)
            }
        }

        imHandler.addImListener(chatHandler)

        _nettyClient.sendMessage(IMMessage(MessageType.GROUP_SIGN, 1, 0, channelId, null, null))

        return channel

    }

    fun closeChannel() {
        if (this::chatHandler.isLateinit) {
            imHandler.removeImListener(chatHandler)
        }
        channel.close()
    }

    fun sendLiveComment(channelId: Long, message: String) {
        viewModelScope.launch {
            userInfoDao.selectOne().collectLatest { userInfo ->
                if (userInfo != null) {
                    nettyClient.sendMessage(IMMessage(MessageType.GROUP_MESSAGE, 1, userInfo.userId, channelId, userInfo.nickname, message.trim()))
                }
            }
        }
    }

}